package com.joysuch.wwyt.bp.controller;


import cn.zlg.common.springmvc.validate.constraints.NotNull;
import com.google.common.collect.Lists;
import com.joysuch.wwyt.bp.bean.BpInspectPlanSearchBean;
import com.joysuch.wwyt.bp.bean.inspect.BpInspectManageDto;
import com.joysuch.wwyt.bp.bean.inspect.BpInspectPlanBean;
import com.joysuch.wwyt.bp.bean.inspect.BpInspectTaskQueryBean;
import com.joysuch.wwyt.bp.bean.inspect.BpInspectTaskQueryDto;
import com.joysuch.wwyt.bp.entity.inspect.BpInspectPlan;
import com.joysuch.wwyt.bp.service.BpInspectPlanService;
import com.joysuch.wwyt.core.bean.SimpleSelectListBean;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.common.util.PageDataUtils;
import com.joysuch.wwyt.core.entity.BaseImageRepository;
import com.joysuch.wwyt.core.repository.BaseImageRespositoryDao;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/bp/inspect-plan")
@Api(tags = "巡检-检查计划管理")
@CrossOrigin
public class BpInspectPlanController {

    @Autowired
    private BpInspectPlanService bpInspectPlanService;
    @Autowired
    private BaseImageRespositoryDao imageRepositoryDao;
    @Value("${wwyt.image.upload.dir}")
    private String appUploadFolder;


    @GetMapping("/list")
    @ApiOperation(value = "检查计划列表", response = BpInspectPlan.class)
    public ResultBean list(Pageable pageable, BpInspectPlanSearchBean searchBean) {
        pageable = PageDataUtils.addOrderByDesc(pageable, "createTime");
        Page<BpInspectPlan> page = bpInspectPlanService.list(pageable,searchBean);
        return ResultBean.pageData(page.getContent(), page.getTotalElements());
    }

    @PostMapping("/save")
    @ApiOperation(value = "保存检查计划")
    @RequiresPermissions("bp:inspect-plan:save")
    public ResultBean save(@RequestBody @Valid BpInspectPlanBean bean) {
        return bpInspectPlanService.save(bean);
    }

    @GetMapping("/delete/{id}")
    @ApiOperation(value = "根据检查计划ID删除")
    @RequiresPermissions("bp:inspect-plan:delete")
    @ApiImplicitParam(name = "id", value = "检查计划ID", paramType = "path", required = true)
    public ResultBean delete(@PathVariable Long id) {
        bpInspectPlanService.deleteById(id);
        return ResultBean.defaultSuccessResult();
    }

    @GetMapping("/get/{id}")
    @ApiOperation(value = "根据检查计划ID查询")
    @ApiImplicitParam(name = "id", value = "检查计划ID", paramType = "path", required = true)
    public ResultBean getById(@PathVariable Long id) {
        return ResultBean.success(bpInspectPlanService.getById(id));
    }

    @GetMapping("/get/{id}/{appTaskId}")
    @ApiOperation(value = "根据检查计划ID查询-app端")
    @ApiImplicitParam(name = "id", value = "检查计划ID", paramType = "path", required = true)
    public ResultBean getById(@PathVariable Long id, @PathVariable Long appTaskId) {
        return bpInspectPlanService.appGetById(id, appTaskId);
    }

    @GetMapping("/open/{id}")
    @ApiOperation(value = "检查计划启用")
    @RequiresPermissions("bp:inspect-plan:open")
    @ApiImplicitParam(name = "id", value = "检查计划ID", paramType = "path", required = true)
    public ResultBean openById(@PathVariable Long id) {
        return bpInspectPlanService.openOrCloseById(id, 1);
    }

    @GetMapping("/close/{id}")
    @ApiOperation(value = "检查计划停用")
    @RequiresPermissions("bp:inspect-plan:close")
    @ApiImplicitParam(name = "id", value = "检查计划ID", paramType = "path", required = true)
    public ResultBean closeById(@PathVariable Long id) {
        return bpInspectPlanService.openOrCloseById(id, 0);
    }

    @GetMapping("/checkPath/{id}")
    @ApiOperation(value = "查看路线")
    @RequiresPermissions("bp:inspect-plan:checkPath")
    @ApiImplicitParam(name = "id", value = "检查计划ID", paramType = "path", required = true)
    public ResultBean checkPath(@PathVariable Long id) {
        return bpInspectPlanService.checkPath(id);
    }

    @GetMapping("/app/inspectManage/needFinish")
    @ApiOperation(value = "app-点检管理-待完成", response = BpInspectManageDto.class)
    public ResultBean inspectManageNeedFinish(Pageable pageable) {
        return bpInspectPlanService.inspectManageNeedFinish(pageable);
    }

    @GetMapping("/app/inspectManage/alreadyFinish")
    @ApiOperation(value = "app-点检管理-已完成", response = BpInspectManageDto.class)
    public ResultBean inspectManageAlreadyFinish(Pageable pageable) {
        return bpInspectPlanService.inspectManageAlreadyFinish(pageable);
    }

    @GetMapping("/app/inspectManage/unFinish")
    @ApiOperation(value = "app-点检管理-未完成", response = BpInspectManageDto.class)
    public ResultBean inspectManageUnFinish(Pageable pageable) {
        return bpInspectPlanService.inspectManageUnFinish(pageable);
    }

    @GetMapping("/app/init")
    @ApiOperation(value = "app-登录成功后轮询调用", response = BpInspectManageDto.class)
    public ResultBean init() {
        return bpInspectPlanService.appInit();
    }

    @GetMapping("/app/startCheck/{id}")
    @ApiOperation(value = "app-点击开始检查 --有返回数据，则立即调检查记录模块的save接口", response = BpInspectManageDto.class)
    @ApiImplicitParam(name = "id", value = "任务表id - 即BpAppPlanTask", paramType = "path", required = true)
    public ResultBean startCheck(@PathVariable Long id) {
        return bpInspectPlanService.startCheck(id);
    }

    @GetMapping("/pointId/relatedOrNot/{pointId}")
    @ApiOperation(value = "检查点是否有检查计划引用  --空集代表没有", response = List.class)
    @ApiImplicitParam(name = "pointId", value = "检查点id", paramType = "path", required = true)
    public ResultBean relatedOrNot(@PathVariable Long pointId) {
        return bpInspectPlanService.relatedOrNot(pointId);
    }

    @GetMapping("/app/checkFinish/{recordId}")
    @ApiOperation(value = "app端点击检查结束按钮--此接口已作废")
    @ApiImplicitParam(name = "recordId", value = "记录表id", paramType = "path", required = true)
    public ResultBean checkFinish(@PathVariable @NotNull Long recordId) {
        return bpInspectPlanService.checkFinish(recordId, 0, null);
    }

    @GetMapping("/plan/produce/insider")
    public ResultBean planProduceIndoor() {
        bpInspectPlanService.initAllTask();
        return ResultBean.defaultSuccessResult();
    }

    @GetMapping("/task-query")
    @ApiOperation(value = "点检任务查询", response = BpInspectTaskQueryDto.class)
    public ResultBean taskQuery(BpInspectTaskQueryBean bean) {
        return bpInspectPlanService.taskQuery(bean);
    }

    @PostMapping("/app/uploadImage")
    @ApiOperation(value = "app端上传图片")
    public ResultBean uploadImage(@RequestPart("image") MultipartFile[] image) {
        List<String> pathList = Lists.newArrayList();
        for (MultipartFile multipartFile : image) {
            String path = UUID.randomUUID().toString().replaceAll("-", "") + ".jpg";
            File newFile = new File(appUploadFolder + File.separator + "app" + File.separator + path);
            try {
                File file = new File(appUploadFolder + File.separator + "app");
                if (!file.exists()) {
                    FileUtils.forceMkdir(file);
                }
                if (!newFile.exists()) {
                    newFile.createNewFile();
                }
                multipartFile.transferTo(newFile);
                log.info("新文件路径：" + appUploadFolder + File.separator + "app" + File.separator + path);
            } catch (IOException e) {
                log.error(e.getMessage());
                e.printStackTrace();
            }
            BaseImageRepository imageRepository = new BaseImageRepository();
            imageRepository.setOriginPath("app" + File.separator + path);
            imageRepository.setUploadTime(new Date());
            BaseImageRepository save = imageRepositoryDao.save(imageRepository);
            pathList.add(save.getOriginPath());
        }
        return ResultBean.success(pathList);
    }


    @GetMapping("/getTaskList")
    @ApiOperation(value = "获取计划列表", response = SimpleSelectListBean.class)
    public ResultBean getTaskList(String flag ) {
        return bpInspectPlanService.getTaskList(flag);
    }
}
